<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use mbilling\BillingBundle\Model\OrdersModel;
use mbilling\BillingBundle\Model\OrdersSharedModel;
use mbilling\BillingBundle\Model\OrdersVpsModel;
use mbilling\BillingBundle\Model\OrdersSharedTarifModel;
use mbilling\BillingBundle\Model\OrdersVpsTarifModel;
use mbilling\BillingBundle\Model\UsersBillsModel;
use mbilling\BillingBundle\Model\UsersLogsModel;
use mbilling\BillingBundle\Model\UsersModel;
use mbilling\BillingBundle\Model\DomainsModel;
use mbilling\BillingBundle\Entity\orders;
use mbilling\BillingBundle\Entity\usersLogs;
use mbilling\BillingBundle\Other\Date;

use mbilling\BillingBundle\Form\OrdersForm;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;

class OrdersController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $order_model = new OrdersModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderVps_model = new OrdersVpsModel($em);
        $orderSharedTarif_model = new OrdersSharedTarifModel($em);
        $orderVpsTarif_model = new OrdersVpsTarifModel($em);
        $bill_model = new UsersBillsModel($em);
        $user_model = new UsersModel($em);
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();

        $parameters = array();
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                $orders = $order_model->findByUserId($this->get('session')->get('user')->getId());
            else
                $orders = $order_model->findAll();
        }
        else
            $orders = $order_model->findByUserId($userCurrent->getId());
        
        foreach($orders as $order)
        {
            if ($order->isShared())
            {
                $orderAdv = $orderShared_model->findByOrderId($order->getId());
                $orderAdvTarif = $orderSharedTarif_model->findByPK($orderAdv->getSharedTarif());
            }
            elseif ($order->isVps())
            {
                $orderAdv = $orderVps_model->findByOrderId($order->getId());
                $orderAdvTarif = $orderVpsTarif_model->findByPK($orderAdv->getVpsTarif());
            }
            $bill = $bill_model->findByOrderId($order->getId());
            $user = $user_model->findByPK($order->getUserId());
            array_push($parameters, array('order'       => $order,
                                          'orderAdv'    => $orderAdv,
                                          'tarif'       => $orderAdvTarif,
                                          'bill'        => $bill,
                                          'user'        => $user));
        }

        /*$jabber = $this->get('jabber');
        if ($jabber->check())
        {
            $id = $jabber->sendMessage(16, array('password' => '123123'));
            $result = $jabber->waitMessage($id);
            print_r($result);
            $id2 = $jabber->sendMessage(11, array('prefix' => 'test1_'));
            $result = $jabber->waitMessage($id2);
            print_r($result);
        }*/
        
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders:user_index.html.twig', array('parameters' => $parameters));
            else
                return $this->render('BillingBundle:Orders:admin_index.html.twig', array('parameters' => $parameters));
        }
        else
            return $this->render('BillingBundle:Orders:user_index.html.twig', array('parameters' => $parameters));
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $order_model = new OrdersModel($em);
        
        $order = new orders();
        $order_model->create($order->initDefaultEntity());//создание по умолчанию

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->createPermissionsForOne($order, $userCurrent, MaskBuilder::MASK_OWNER);
        $acl->createPermissionsForAllAdmins($order);
        
        return new RedirectResponse($this->generateUrl('orders_show'));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $order_model = new OrdersModel($em);
        $order = $order_model->findByPK($id);
        $securityContext = $this->container->get('security.context');

        $acl = $this->get('acl');
        $acl->checkPermissions($order, 'EDIT');

        $form = $this->createForm(new OrdersForm, $order);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $order_model->create($form->getData());
                return new RedirectResponse($this->generateUrl('orders_show'));
            }
        }
        return $this->render('BillingBundle:Orders:update.html.twig', array('form' => $form->createView()));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $order_model = new OrdersModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderVps_model = new OrdersVpsModel($em);
        $domain_model = new DomainsModel($em);
        
        $order = $order_model->findByPK($id);
        if ($order->isShared())
        {
            $orderAdv = $orderShared_model->findByOrderId($id);
            $domain = $domain_model->findByOrderId($order->getId());
        }
        elseif ($order->isVps())
        {
            $orderAdv = $orderVps_model->findByOrderId($id);
        }
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($order, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($order, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($order, $userCurrent);
        $acl->removePermissionsForAllAdmins($order);
        $acl->checkPermissions($orderAdv, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($orderAdv, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($orderAdv, $userCurrent);
        $acl->removePermissionsForAllAdmins($orderAdv);

        if ($order->isShared())
        {
            $orderShared_model->removeByOrderId($order->getId());

            $acl->checkPermissions($domain, 'DELETE');
            if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                $acl->removePermissionsForOne($domain, $this->get('session')->get('user'));
            else
                $acl->removePermissionsForOne($domain, $userCurrent);
            $acl->removePermissionsForAllAdmins($domain);
            $domain_model->removeByPK($domain->getId());
        }
        elseif ($order->isVps())
        {
            $orderVps_model->removeByOrderId($order->getId());
        }
        
        $bill_model = new UsersBillsModel($em);
        $bill = $bill_model->findByOrderId($order->getId());
        $acl->checkPermissions($bill, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($bill, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($bill, $userCurrent);
        $acl->removePermissionsForAllAdmins($bill);
        
        $bill_model->removeByOrderId($order->getId());

        $log_model = new UsersLogsModel($em);
        $log = new usersLogs();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $log->setUserId($this->get('session')->get('user')->getId());
        else
            $log->setUserId($userCurrent->getId());
        $log->setActionTypeId('2');//удаление заказа
        $log->setOrderId($order->getId());
        $log_model->create($log);

        $order_model->removeByPK($order->getId());
        
        return new RedirectResponse($this->generateUrl('orders_show'));
    } 
    public function personalCabinetAction()
    {
        return $this->render('BillingBundle:Orders:user_personal_cabinet.html.twig', array());
    }
}